<?php
/**
 * 拼团自动退款(自动申请退款)
 *
 * by abc.com 多用户商城
 *
 *
 */
// ignore_user_abort(true);//关闭浏览器也能继续运行
// set_time_limit(0);
//by abc.com
//use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');
class member_auto_refundControl{
    
    public function __construct(){
        register_shutdown_function(array($this,"shutdown"));
    }
    /**
     * 自动退款功能
     * D:\phpStudy\WWW\lxs\mobile\control\member_auto_refund.php
     * 解决方案，运行一遍，永远执行。
     * 有待测试
     */
    public function indexOp(){

            //找到未成团的拼团
            $groupbuy_team_model=Model('groupbuy_team');
            //$condition['end_time']=array('lt',time());//结束时间比现在小
            $condition['pay_status']=1;
            //$condition['team_number']=array('gt','record_num');
            //var_export($condition);die;
            $fail_team_list=$groupbuy_team_model->get_team_faile_list($condition);
               echo '<br><br><pre>';
            //var_export($fail_team_list);die;
            //查找拼团订单
            if (empty($fail_team_list)){
                echo '$fail_team_list没有数据';
            }
            
            $order_model=Model('order');
            foreach ($fail_team_list as $key=>$val){
                //找到对应拼团订单
                $condition_or['team_id']=$fail_team_list[$key]['team_id'];
                //$condition_or['order_lock']=array('gt',0);
                $condition_or['order_state']=20;
                $condition_or['lock_state'] = 0;//查找申请退款未锁定的订单
                //echo json_encode($condition_or);die;
                $team_order_list=$order_model->getNormalOrderList($condition_or);//返货该team_id下的所有订单
                  /*  echo '<BR><BR><pre>';
                echo json_encode($team_order_list); */
                if (empty($team_order_list)){
                    echo '$team_order_list没有数据\n';
                }else{
                    foreach ($team_order_list as $key=>$value){//起碼有一個數據
                    //echo $team_order_list[$key]['order_id'];die;
                    $order_id = intval($team_order_list[$key]['order_id']);
                    $condition = array();
                    //$condition['buyer_id'] = $fail_team_list[$key]['team_id'];
                    $condition['order_id'] = $order_id;
                    $condition['refund_lock'] = 0;//查找申请退款未锁定的订单
                    //返回订单信息(从order表中拿到的数据)
                    $model_refund = Model('refund_return');
                    $order = $model_refund->getRightOrderList($condition);
                    /*  echo '<pre>';
                     var_export($order);die;  */
                    $order_amount = $order['order_amount'];//订单金额
                    $condition = array();
                    $condition['buyer_id'] = $order['buyer_id'];
                    $condition['order_id'] = $order['order_id'];
                    $condition['goods_id'] = '0';
                    $condition['seller_state'] = array('lt','3');
                    //取出退款记录
                    //echo json_encode($condition);die;
                    $refund_list = $model_refund->getRefundReturnList($condition);
                    /*  if (empty($refund_list)){
                     echo '$refund_list没有数据';
                     } */
                    
                    /*  echo '<pre>';
                     var_export($refund_list);die; */
                    $refund = array();
                    if (!empty($refund_list) && is_array($refund_list)) {
                        $refund = $refund_list[0];
                    }
                    $model_trade = Model('trade');
                    $order_paid = $model_trade->getOrderState('order_paid');//订单状态20:已付款
                    //echo $order_paid;
                    $payment_code = $order['payment_code'];//支付方式
                    //echo $payment_code;die;
                    //echo $order['order_state'];die;
                    //退款id>0                或者  //订单状态20!=支付状态20
                    if ($refund['refund_id'] > 0 || $order['order_state'] != $order_paid || $payment_code == 'offline') {//检查订单状态,防止页面刷新不及时造成数据错误
                        output_error($refund['refund_id'].'---'.$order['order_id'].'--操作失败，请检查订单状态!--'.$order['order_state']);
                    }
                    //echo 11;die;
                    $_POST['buyer_message']='拼团不成功，自动申请退款';
                    $refund_array = array();
                    $refund_array['refund_type'] = '1';//类型:1为退款,2为退货
                    $refund_array['seller_state'] = '1';//状态:1为待审核,2为同意,3为不同意
                    $refund_array['order_lock'] = '2';//锁定类型:1为不用锁定,2为需要锁定
                    $refund_array['goods_id'] = '0';
                    $refund_array['order_goods_id'] = '0';
                    $refund_array['reason_id'] = '0';
                    $refund_array['reason_info'] = '取消订单，全部退款';
                    $refund_array['goods_name'] = '订单商品全部退款';
                    $refund_array['refund_amount'] = ncPriceFormat($order_amount);
                    $refund_array['buyer_message'] = $_POST['buyer_message'];
                    $refund_array['add_time'] = time();
                    //var_export($refund_array);die;
                    $pic_array = array();
                    //$pic_array['buyer'] = $this->upload_pic();//上传凭证
                    //$info = serialize($pic_array);
                    //$refund_array['pic_info'] = $info;
                    //增加退款退货，保存退款申请
                    //die;
                    $state = $model_refund->addRefundReturn($refund_array,$order);
                    //设置订单refund_lock=1；
                    //$data,$condition
                   /*  $data['refund_lock']=1;
                    $condition['order_id']=$order['order_id'];
                    $order_model->editOrder($data,$condition); */
                   
                     if ($state) {
                         echo '退款申请成功\n';
                        //这里可以操作发送发货短信
                        if (!empty($team_order_list[$key]['buyer_name'])) {
                    
                            $mobile = $team_order_list[$key]['buyer_name'];
                             
                            //要提供三个参数
                            //用户手机号，商品名，订单号
                            //【乐相随】亲爱的{name}，您购买的宝贝（订单号：{123456789}）已由{物流公司}运送。可登陆乐相随查看物流详情。祝您生活愉快~
                            $data['buyer_name']=$mobile;
                            $data['order_sn']=$order['order_sn'];//订单号
                            //个性化短信
                            $result=$this->_testSms($data);
                            if(!$result){
                                echo '消息未发出<br>';
                                //output_data(array('status'=>'error','msg'=>'消息未发出'));
                            }
                        }
                        //锁定订单
                        $model_refund->editOrderLock($order_id);
                        echo 'ok\n';
                        //output_data(array('status'=>'success','msg'=>'操作成功！'));
                    } else {
                        echo ('操作失败!\n');
                    } 
                    
                }
                }
               
                
            }
//             sleep($time);
//             file_get_contents($url);
          
            $this->success_team();
            
    }
    
    /**
     * 拼团成功发送短信
     */
    public function success_teamOp(){
        //找到未成团的拼团
        $groupbuy_team_model=Model('groupbuy_team');
        //$condition['end_time']=array('lt',time());//结束时间比现在小
        $condition['pay_status']=1;
        //$condition['team_number']=array('gt','record_num');
        //var_export($condition);die;
        $get_team_success_list=$groupbuy_team_model->get_team_success_list($condition);

        //var_export($fail_team_list);die;
        //查找拼团订单
        if (empty($get_team_success_list)){
            echo '$get_team_success_list没有数据';
        }else{
            $order_model=Model('order');
            foreach ($get_team_success_list as $key_suc=>$val_suc){
                //找到对应拼团订单
                $condition_or['team_id']=$get_team_success_list[$key_suc]['team_id'];
                //$condition_or['order_lock']=array('gt',0);
                $condition_or['order_state']=20;
                $condition_or['lock_state'] = 0;//查找申请退款未锁定的订单
                //echo json_encode($condition_or);die;
                $team_order_list=$order_model->getNormalOrderList($condition_or);//返货该team_id下的所有订单
                  /*  echo '<BR><BR><pre>';
                echo json_encode($team_order_list); */
                if (empty($team_order_list)){
                    echo '$team_order_list没有数据\n';
                }else{
                    foreach ($team_order_list as $key=>$value){//起碼有一個數據
                    
                    }
                }
            }
        }
        
        
        
    }
    
    /*
     * crontab -e
     * 1 * * * * /home/wwwroot/default/shop/mobile/control/auto.php
     * 30（分）     5（时）       *（天）           *（月）     *（星期，0表示星期天）    执行命令 
     */
    
    /**
     * 定时任务，需要操作系统协助
     * D:\phpStudy\WWW\lxs\mobile\control\member_auto_refund.php
     * 解决方案，运行一遍，永远执行。
     * 有待测试
     */
    public function timer_taskOp(){
         
      
            //找到未成团的拼团
            $groupbuy_team_model=Model('groupbuy_team');
            $condition['end_time']=array('lt',time());//结束时间比现在小
            $condition['pay_status']=1;
            $condition['team_number']=array('gt','record_num');
            $fail_team_list=$groupbuy_team_model->get_team_list(0,$condition);
            /*  echo '<pre>';
             var_export($fail_team_list);die; */
            //查找拼团订单
            $order_model=Model('order');
            foreach ($fail_team_list as $key=>$val){
                //找到对应拼团订单
                $condition_or['team_id']=$fail_team_list[$key]['team_id'];
                //$condition_or['order_lock']=array('gt',0);
                $condition_or['order_state']=20;
                $condition['refund_lock'] = 0;//查找申请退款未锁定的订单
                $team_order_list=$order_model->getNormalOrderList($condition_or);//返货该team_id下的所有订单
                /* echo '<pre>';
                 json_encode($team_order_list);die;  */
                foreach ($team_order_list as $key=>$value){
                    //echo $team_order_list[$key]['order_id'];die;
                    $order_id = intval($team_order_list[$key]['order_id']);
                    $condition = array();
                    //$condition['buyer_id'] = $fail_team_list[$key]['team_id'];
                    $condition['order_id'] = $order_id;
                    $condition['refund_lock'] = 0;//查找申请退款未锁定的订单
                    //返回订单信息(从order表中拿到的数据)
                    $model_refund = Model('refund_return');
                    $order = $model_refund->getRightOrderList($condition);
                    /*  echo '<pre>';
                     var_export($order);die;  */
                    $order_amount = $order['order_amount'];//订单金额
                    $condition = array();
                    $condition['buyer_id'] = $order['buyer_id'];
                    $condition['order_id'] = $order['order_id'];
                    $condition['goods_id'] = '0';
                    $condition['seller_state'] = array('lt','3');
                    //取出退款记录
                    $refund_list = $model_refund->getRefundReturnList($condition);
                    /*  echo '<pre>';
                     var_export($refund_list);die; */
                    $refund = array();
                    if (!empty($refund_list) && is_array($refund_list)) {
                        $refund = $refund_list[0];
                    }
                    $model_trade = Model('trade');
                    $order_paid = $model_trade->getOrderState('order_paid');//订单状态20:已付款
                    //echo $order_paid;
                    $payment_code = $order['payment_code'];//支付方式
                    //echo $payment_code;die;
                    //echo $order['order_state'];die;
                    //退款id>0                或者  //订单状态20!=支付状态20
                    if ($refund['refund_id'] > 0 || $order['order_state'] != $order_paid || $payment_code == 'offline') {//检查订单状态,防止页面刷新不及时造成数据错误
                        output_error($order['order_id'].'操作失败，请检查订单状态!'.$order['order_state']);
                    }
                    //echo 11;die;
                    $_POST['buyer_message']='拼团不成功，自动申请退款';
                    $refund_array = array();
                    $refund_array['refund_type'] = '1';//类型:1为退款,2为退货
                    $refund_array['seller_state'] = '1';//状态:1为待审核,2为同意,3为不同意
                    $refund_array['order_lock'] = '2';//锁定类型:1为不用锁定,2为需要锁定
                    $refund_array['goods_id'] = '0';
                    $refund_array['order_goods_id'] = '0';
                    $refund_array['reason_id'] = '0';
                    $refund_array['reason_info'] = '取消订单，全部退款';
                    $refund_array['goods_name'] = '订单商品全部退款';
                    $refund_array['refund_amount'] = ncPriceFormat($order_amount);
                    $refund_array['buyer_message'] = $_POST['buyer_message'];
                    $refund_array['add_time'] = time();
    
                    $pic_array = array();
                    //$pic_array['buyer'] = $this->upload_pic();//上传凭证
                    //$info = serialize($pic_array);
                    //$refund_array['pic_info'] = $info;
                    //增加退款退货，保存退款申请
                    $state = $model_refund->addRefundReturn($refund_array,$order);
                    //设置订单refund_lock=1；
                    //$data,$condition
                    /*  $data['refund_lock']=1;
                     $condition['order_id']=$order['order_id'];
                     $order_model->editOrder($data,$condition); */
        
                    if ($state) {
                        //这里可以操作发送发货短信
                        if (!empty($team_order_list[$key]['buyer_name'])) {
        
                            $mobile = $team_order_list[$key]['buyer_name'];
                             
                            //要提供三个参数
                            //用户手机号，商品名，订单号
                            //【乐相随】亲爱的{name}，您购买的宝贝（订单号：{123456789}）已由{物流公司}运送。可登陆乐相随查看物流详情。祝您生活愉快~
                            $data['buyer_name']=$mobile;
                            $data['order_sn']=$order['order_sn'];//订单号
                            //个性化短信
                            $result=$this->_testSms($data);
                            if(!$result){
                                echo '消息未发出';
                                //output_data(array('status'=>'error','msg'=>'消息未发出'));
                            }
                        }
        
        
                        //锁定订单
                        $model_refund->editOrderLock($order_id);
                        echo 'ok';
                        //output_data(array('status'=>'success','msg'=>'操作成功！'));
                    } else {
                        echo ('操作失败!');
                    }
                }
            }

    }
    
    /*
     * 发送短信
     */
    private function _testSms($data){
        //echo json_encode($data);die;
        $sms = new Sms();
         
        $mobile = $data['buyer_name'];
        $content = '【乐相随】亲爱的'.$data['buyer_name'].'用户，您参与的拼团（拼团订单号：'.$data['order_sn'].'）未成功，自动为您申请费退款，等待商家与您沟通';
        $result = $sms->send($mobile,$content);
        return $result;
    }
    
}
    